package org.jdsm.gae.komarichyn.blog;

import com.opensymphony.xwork2.ActionSupport;
import org.jdsm.flow.core.simpleblog.IBlogService;
import org.jdsm.flow.core.simpleblog.IPost;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * User: mikom
 * Date: 11/7/12
 * Time: 2:06 PM
 */
public class BlogAction extends ActionSupport {

    private static final Logger log = LoggerFactory.getLogger(BlogAction.class);

    @Resource
    IPost post;
    @Resource
    IBlogService blogService;

    /**
     * save new post. Data injects in IPost instance if it was passed correct.
     * For example: for fulling IPost object to need pass data in format
     * post.title<br/>
     * post.description<br/>
     * post.keyWords<br/>
     * post.shortDescription<br/>
     * post.content<br/>
     * another params will be default {@link IPost}
     * All text params should be has length less 256 characters extend post.content
     *
     * @return to result page
     */
    public String savePost() {
        blogService.saveOrUpdate(post);
        return SUCCESS;
    }

    /**
     * remove post. removing post by identifier if it exist in DB
     * The post will be looking by post.id. If we could not find post by post.id
     * we make forward on dashboard anywhere.
     * @return to result page
     * @throws Exception
     */
    public String removePost() throws Exception {
        post = blogService.findPost(post);
        log.debug("preparing post:{} for removing", post);
        if(post == null){
            log.error("post not found");
            return INPUT;
        }
        blogService.delete(post);
        return SUCCESS;
    }
    /**
     * load post by identifier and refer it to this.post<br/>
     *
     * @return to result page
     */
    public String viewPost() {
        post = blogService.findPost(post);
        log.debug("preparing post :{} for displaying", post);
        return SUCCESS;
    }

    /**
     * fetch posts from DB. This method returns latest post which has no flag post.hidden as true,
     * has no flag post.draft as true
     *
     * @return latest posts by created date
     */
    public List<IPost> getLatestPost() {
        List<IPost> latest = blogService.findLatestPosts(10);
        log.debug("found {} posts:{}", latest.size(), latest);
        return latest;
    }

    public IPost getPost() {
        return post;
    }

    public void setPost(IPost post) {
        this.post = post;
    }

}
